/**
 * @description  : 手写签名组件
 * @descriptionDetail : 手写签名组件
 * @copyright    : 浙江烟草
 * @author       : mc
 * @create       : 2022-10-03 17:21:22
 */
<template>
  <view class="signature" :class="{'visible':show}" v-if="syncShow" @touchmove.stop.prevent="moveHandle">
    <view class="mask" />
    <view :class="isHor ? 'long-content' : 'content'">
      <view class="header">
        <span class="extra-info">{{ extraInfoTitle }}</span>
        <u-icon class="icon-close" name="close" size="22px" @tap="close"></u-icon>
      </view>
      <canvas
        class="sign-canvas"
        :canvas-id="canvasId"
        disable-scroll="true"
        @touchmove="move"
        @touchstart="start($event)"
        @touchend="end"
        @touchcancel="cancel"
        @longtap="longtap"
        @error="error"
      />
      <view class="sign-btns" v-if="!disabled">
        <u-button type="primary" size="medium" v-if="!mustHor" @tap="reviseCanvas">
          <span class="btn-text">旋转</span>
        </u-button>
        <u-button size="medium" @tap="clear">
          <span class="btn-text">清除</span>
        </u-button>
        <u-button type="primary" size="medium" @tap="save">
          <span class="btn-text">保存</span>
        </u-button>
      </view>
    </view>
  </view>
</template>

<script>
let content = null;
let touchs = [];
let canvasw = 0;
let canvash = 0;
// 获取系统信息
uni.getSystemInfo({
  success: function(res) {
    canvasw = res.windowWidth;
    canvash = res.windowHeight * 0.8; // 高度取页面高度的80%，如果改动此值，css也要改一下
  },
})
export default{
  name:'Signature',
  props:{
    visible: {
      type: Boolean,
      default: false,
    },
    canvasId: {
      type: String,
      default: 'sign-canvas-' + new Date().getTime(),
    },
    extraInfo: {
      type: String,
      default: "点击下方空白区域签名",
    },
    disabled:{
      // 是否禁用..禁用后没有下面的按钮
      type: Boolean,
      default: false,
    },
    destWidth:{
      type: Number,
      default: -1,
    },
    destHeight:{
      type: Number,
      default: -1,
    },
    mustHor:{ // 强制横屏
      type:Boolean,
      default: false,
    },
  },
  data(){
    return{
      show:false,
      syncShow: false,
      signImage:'',
      hasDh:false,
      isHor: false, // 是否横向展示
      extraInfoTitle: this.extraInfo,
    }
  },
  watch:{
    visible(val) {
      this.syncShow = val;
      this.show = val;
      this.getInfo()
    },
  },
        
  created(options) {
    this.syncShow = this.visible
    this.isHor = this.mustHor;
    this.getInfo()
    setTimeout(() => {
      this.show = this.visible;
    }, 100)
  },
  methods:{
    // 旋转
    reviseCanvas() {
      // 清空已绘制内容
      this.clear();
      this.isHor = !this.isHor;
      this.extraInfoTitle = this.isHor ? "点击右侧空白区域签名" : "点击下方空白区域签名";
    },
    getInfo(){
      // 获得Canvas的上下文
      content = uni.createCanvasContext(this.canvasId, this)
      // 设置线的颜色
      content.setStrokeStyle("#000")
      // 设置线的宽度
      content.setLineWidth(5)
      // 设置线两端端点样式更加圆润
      content.setLineCap('round')
      // 设置两条线连接处更加圆润
      content.setLineJoin('round')
    },
    close() {
      this.show = false;
      this.hasDh = false;
      this.$emit('close')
    },
    moveHandle(){
                
    },
    // 画布的触摸移动开始手势响应
    start(e){
      let point = {
        x: e.touches[0].x,
        y: e.touches[0].y,
      }
      touchs.push(point);
      this.hasDh = true
    },
    // 画布的触摸移动手势响应
    move(e) {
      let point = {
        x: e.touches[0].x,
        y: e.touches[0].y,
      }
      touchs.push(point)
      if (touchs.length >= 2) {
        this.draw(touchs)
      }
    },
            
    // 画布的触摸移动结束手势响应
    end(e) {
      // 清空轨迹数组
      for (let i = 0; i < touchs.length; i++) {
        touchs.pop()
      }
    },
            
    // 画布的触摸取消响应
    cancel(e) { },
            
    // 画布的长按手势响应
    longtap(e) {
      // console.log("长按手势" + e)
    },
            
    error(e) {
      console.error(e);
    },
            
    // 绘制
    draw(touchs) {
      let point1 = touchs[0]
      let point2 = touchs[1]
      content.moveTo(point1.x, point1.y)
      content.lineTo(point2.x, point2.y)
      content.stroke()
      content.draw(true);
      touchs.shift()
    },
    // 清除操作
    clear() {
      // 清除画布
      content.clearRect(0, 0, canvasw, canvash)
      content.draw(true)
      this.hasDh = false;
      this.$emit('clear');
    },
    save(){
      let that = this;
      if(!this.hasDh){
        uni.showToast({title:'请签名',icon:'none',})
        return;
      }
      uni.showLoading({title:'生成中...',mask:true,})
      setTimeout(() => {
        let param = {
          canvasId: this.canvasId,
          success: function(res) {
            console.log("签名图片", res);
            // 如果是横向展示，签名图片旋转一下
            if (that.isHor) {
              that.rotateBase64Img(res.tempFilePath, 270).then(imgData => {
                that.signImage = imgData;
                that.$emit('save', imgData);
                uni.hideLoading()
                that.hasDh = false;
                that.show = false;
              });
              return;
            }
            that.signImage = res.tempFilePath;
            that.$emit('save', res.tempFilePath);
            uni.hideLoading()
            that.hasDh = false;
            that.show = false;
          },
          fail:function(err){
            console.log(err)
            uni.hideLoading()
          },
        };
        if(this.destWidth != -1 && this.destHeight != -1){
          param.destWidth = this.destWidth;
          param.destHeight = this.destHeight;
        }
        uni.canvasToTempFilePath(param,this)
      },100)
    },
    // 旋转图片
    rotateBase64Img(src, edg) {
      return new Promise((resolve, reject) => {
        let canvas = document.createElement("canvas");
        let ctx = canvas.getContext("2d");
      
        let imgW;// 图片宽度
        let imgH;// 图片高度
        let size;// canvas初始大小
      
        if (edg % 90 != 0) {
          console.error("旋转角度必须是90的倍数!");
          reject('旋转角度必须是90的倍数!');
        }
        (edg < 0) && (edg = (edg % 360) + 360);
        const quadrant = (edg / 90) % 4; // 旋转象限
        const cutCoor = {sx: 0, sy: 0, ex: 0, ey: 0,}; // 裁剪坐标
        let image = new Image();
        image.crossOrigin = "anonymous";
        image.src = src;
      
        image.onload = function () {
          imgW = image.width;
          imgH = image.height;
          size = imgW > imgH ? imgW : imgH;
      
          canvas.width = size * 2;
          canvas.height = size * 2;
          switch (quadrant) {
          case 0:
            cutCoor.sx = size;
            cutCoor.sy = size;
            cutCoor.ex = size + imgW;
            cutCoor.ey = size + imgH;
            break;
          case 1:
            cutCoor.sx = size - imgH;
            cutCoor.sy = size;
            cutCoor.ex = size;
            cutCoor.ey = size + imgW;
            break;
          case 2:
            cutCoor.sx = size - imgW;
            cutCoor.sy = size - imgH;
            cutCoor.ex = size;
            cutCoor.ey = size;
            break;
          case 3:
            cutCoor.sx = size;
            cutCoor.sy = size - imgW;
            cutCoor.ex = size + imgH;
            cutCoor.ey = size + imgW;
            break;
          }
      
          ctx.translate(size, size);
          ctx.rotate(edg * Math.PI / 180);
          ctx.drawImage(image, 0, 0);
      
          let imgData = ctx.getImageData(cutCoor.sx, cutCoor.sy, cutCoor.ex, cutCoor.ey);
          if (quadrant % 2 == 0) {
            canvas.width = imgW;
            canvas.height = imgH;
          } else {
            canvas.width = imgH;
            canvas.height = imgW;
          }
          ctx.putImageData(imgData, 0, 0);
          resolve(canvas.toDataURL());
        };
      });
    },
      
  },
}
</script>

<style lang="scss" scoped>
.signature.visible {
    visibility: visible
}
.signature {
    display: block;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    overflow: hidden;
    z-index: 11;
    height: 100vh;
    visibility: hidden;
    .mask {
        display: block;
        opacity: 0;
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, .4);
        transition: opacity .3s;
    }
    
    .content {
        display: block;
        position: absolute;
        top: 0;
        left: 0;
        bottom:0;
        right: 0;
        margin: auto;
        width:94%;
        height: 85%;
        background: #fff;
        border-radius: 8upx;
        box-shadow: 0px 3px 3px #333;
        .header {
          height: 40px;
          background-color: #f3f3f3;
          .extra-info {
            line-height: 35px;
            padding-left: 10px;
          }
          .icon-close {
            float: right;
            margin-right: 10px;
            margin-top: 8px;
            color: rgb(134, 133, 133);
          }
        }
        .sign-canvas {
            background-color: #fff;
            width: 100%;
            height: calc(100% - 95px);
        }
        .sign-btns {
            padding: 5px 5px;
            height: 55px;
            overflow: hidden;
            position: absolute;
            bottom: 0upx;
            left: 0;
            right: 0;
            margin: auto;
            display: flex;
            justify-content: space-between;
            background-color: #f3f3f3;
        }
    }
    .long-content {
      display: block;
      position: absolute;
      top: 0;
      left: 0;
      bottom:0;
      right: 0;
      margin: auto;
      width:94%;
      height: 85%;
      background: #fff;
      border-radius: 8upx;
      box-shadow: 0px 3px 3px #333;
      .header {
        height: 40px;
        background-color: #f3f3f3;
        .extra-info {
          width: 20px;
          margin: 0 auto;
          line-height: 24px;
          font-size: 20px;
          display: block;
          transform: rotate(90deg);
          height: 32px;
          float: right;
          margin-right: 89px;
        }
        .icon-close {
          float: right;
          margin-right: -100px;
          margin-top: 8px;
          color: rgb(134, 133, 133);
        }
      }
      .sign-canvas {
          background-color: #fff;
          width: 100%;
          height: calc(100% - 95px);
      }
      .sign-btns {
          padding: 5px 5px;
          height: 55px;
          overflow: hidden;
          position: absolute;
          bottom: 0upx;
          left: 0;
          right: 0;
          margin: auto;
          display: flex;
          justify-content: space-between;
          background-color: #f3f3f3;
      }
      .btn-text {
        -webkit-writing-mode: vertical-rl;
        writing-mode: vertical-rl;
        transform: rotate(90deg);
      }
    }
}
.visible .mask {
    display: block;
    opacity: 1
}    
</style>